<?php
Database($_SESSION['cid']);
header("content-type:text/html;charset=utf-8");
class AudienceAction extends Action{

	public function index(){
		$search= $_GET['seach'] == null ? '' 			: $_GET['seach'];
		$order = $_GET['order'] == null ? 'audience_id' : $_GET['order'];
		$asc   = $_GET['asc']	== null ? 'desc'		: $_GET['asc'];

		$rs	  = pageing('audience',7,'',$_GET['seach'],$order.' '.$asc,'time_insert > time_delete','audience_name','',"DB_MEETING");
		foreach($rs['data'] as &$val) {
			$val['audience_department'] = D('Department')->get_department_name_by_id($val['audience_department']);
		}
		$department = D('Department')->get_depart();
		$rs['meeting_category'] = D('Meeting')->get_meeting_categorys();
		$this->assign("department",$department);
		$this->assign("rs",$rs);
		$this->assign("search" , $search);
		$this->display();
	}

	public function forAct(){
		$this->display();
	}

	public function forAct2(){
		$data = page_ajax("audience",10,"",$_POST['search'],'audience_id desc',"1",'audience_name','','DB_MEETING');
		$this->assign("data",$data['data']);
		$this->assign("page",$data['show']);
		$this->display();
	}
	
	public function addAct(){

		if($_FILES['audience_portrait']['name']!='') $this->imgUpload();
		// $post = $_POST['category_id'];
		// unset($_POST['category_id']);
		
		$rs=D('Company/Audience')->add_audience($_POST);
		if($rs){
			$this->success("添加成功!",__URL__);
		} else {
			$this->error("添加失败!");
		}
	}

	public function delAct(){

		$_POST['time_delete'] = time();

		$rs = D('Audience')->upt_audience($_POST);
		if ($rs){
			//unlink($_POST['audience_portrait']);
			echo '{"state":1}';
		}else{
			echo '{"state":0}';
		}
    }
	
//修改通讯录
	public function to_update(){
		if($_GET){
			$audience 	= D('Company/Audience')	 ->get_data_by_audience_id($_GET['audience_id']);
			$amc 	= D('Company/Audience')	 ->get_audience_meeting_category($_GET['audience_id']);
			$type = M('meeting_category' , '' , 'DB_MEETING')->where('time_insert>time_delete')->select();
			$department = D('Company/Department')->get_depart();
			$this->assign('department',$department);
			$this->assign('audience',$audience);
			$this ->assign('amc' , $amc);
			$this ->assign('type' , $type);
			$this->display();
		}
	}

	// 李记辉  修改于2015/01/26
	public function uptAct(){

		if($_FILES['audience_portrait']['name']!='') $this->imgUpload();
        $_POST['time_update']=time();
		$rs = D('Audience')->upt_audience($_POST);
		if($_POST['audience_department'] != $_POST['old_department'])
		{
			D('Audience')   -> update_department_rds($_POST['audience_id'],$_POST['old_department'],$_POST['audience_department']);
			D('Department') -> update_department_time($_POST['audience_department']);
			D('Department') -> update_department_time($_POST['old_department']);
		}

		if($rs){
			$this->success("修改成功!");
		} else {
			$this->error("修改失败！");
		}
	}
	// 李记辉  修改于2015/01/26
	
	public function imgUpload(){
		$audience_image_path = 'Public/Uploads'.'/';
		if(!is_dir($audience_image_path))mkdir($audience_image_path,0777,true);
		$audience_image_path.= 'audience'.'/';
		if(!is_dir($audience_image_path))mkdir($audience_image_path,0777,true);
		$audience_image_path.= $_SESSION['cid'] .'/';
		if(!is_dir($audience_image_path))mkdir($audience_image_path,0777,true);

		import('ORG.Net.UploadFile');
		$config['savePath'] = $audience_image_path;
		$config['allowExts']= array('jpg', 'gif', 'png', 'jpeg');
		$config['maxSize']= 3145728;
		$config['thumb'] = true;
		$config['thumbPrefix'] = 'm_';
		$config['thumbMaxWidth'] = '480';
		$config['thumbMaxHeight'] = '320';
		$config['thumbRemoveOrigin']=true;
		$upload = new UploadFile($config);
		if(!$upload->upload()){
			$this->error($upload->getErrorMsg());
		}else{
			$uploadList = $upload->getUploadFileInfo();
			$_POST['audience_portrait']	=$audience_image_path.$config['thumbPrefix'].$uploadList[0]['savename'];
		}
	}
	
	public function choose_audience(){
		$list = M('audience','','DB_MEETING')->order('audience_username')->select();
		$this->assign('speakerlist',$list);
		$this->assign('action',$_GET['action']);
		$this->assign('type',$_GET['type']);
		$this->display();
	}
	
	public function choose_audience_checkbox(){
		$list = M('audience','','DB_MEETING')->order('audience_username')->select();
		$this->assign('speakerlist',$list);
		$this->assign('action',$_GET['action']);
		$this->display();
	}

	//生成sqlite数据库
	public function create_database_init(){
		try{
			//创建sqlite
			$path=C('PATH_SQLITE_DATABASE').'audience/';
			if(!is_dir($path))mkdir($path,0777,true);
			$path.=$_SESSION['cid'].'/';
			if(!is_dir($path))mkdir($path,0777,true);
			$path.=time().'.db';

			$dbh=new PDO("sqlite:{$path}");
			$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			//audience.db
			$sql .= "CREATE TABLE audience(
				`audience_id` integer PRIMARY KEY,
				`audience_name` Varchar DEFAULT NULL,
				`audience_tel` integer,
				`audience_email` Varchar DEFAULT NULL,
				`audience_position` Varchar DEFAULT NULL,
				`audience_portrait` Varchar DEFAULT NULL,
				`audience_imUsername` Varchar DEFAULT NULL,
				`audience_imPassword` Varchar DEFAULT NULL,
				`audience_department` Varchar DEFAULT NULL
			);";
			$sql.=D('Sqlite')->get_audience_for_sqlite();
			$rs=$dbh->exec($sql);
			if($rs)
				$re=D('Sqlite')->save_sqlite_database($path,1);
			if($re)
				$this->success('已生成最新数据库',__APP__.'/Audience');
		}catch(Exception $e) {
			echo "error!!:$e";
			exit;
		}
	}

	//sqlite
	function get_database_for_sqlite($table,$fields,$field,$last){
		$sql['insert']="select {$fields} from `{$table}` where time_insert>=$last and time_delete < time_insert";
		$add_list 	= M("","","DB_MEETING")->query($sql['insert']);
		if($add_list==null || count($add_list)==0)
			$sql='';
		else{
			$sql='';
			foreach($add_list as $val){
				switch($table){
					case 'agenda_cn':
						$val['exam']=(int)M('course_exam','','DB_MEETING')->where('agenda_id='.$val['agendaId'])->count();
						$sql.="insert into agenda(agenda_id,agenda_title,agenda_subjectId,agenda_tag,agenda_abstraction,agenda_location,agenda_startDate,agenda_startTime,agenda_endDate,agenda_endTime,agenda_speakerId,agenda_groupId,agenda_votes,agenda_beforeClass,agenda_endClass,agenda_category,agenda_lang,agenda_exam)";
						$sql.="values('{$val['agendaId']}','{$val['title']}','{$val['subjectId']}','{$val['tag']}'";
						$sql.=",'{$val['abstraction']}','{$val['location']}','".trim($val['startDate'])."','{$val['startTime']}'";
						$sql.=",'".trim($val['endDate'])."','".trim($val['endTime'])."','{$val['speakerId']}','{$val['groupId']}'";
						$sql.=",'{$val['votes']}','{$val['before_class']}','{$val['end_class']}','{$val['category']}','cn','{$val['exam']}');";
						break;
					case 'speaker_cn':
						$pinyin=strtolower($val['name']);
						$val['nick']=Pinyin($pinyin,1);
						$val['nick']=$val['nick']{0};
						$sql.="insert into speaker(speaker_id,speaker_company,speaker_name,speaker_avatar,speaker_website,speaker_gender,speaker_contactInfo,speaker_briefIntro,speaker_detailIntro,speaker_nick,speaker_sort,speaker_lang,speaker_display)";
						$sql.=" values('{$val['speakerId']}','{$val['company']}','{$val['name']}','{$val['avatar']}'";
						$sql.=",'{$val['website']}','{$val['gender']}','{$val['contactInfo']}','{$val['briefIntro']}'";
						$sql.=",'{$val['detailIntro']}','{$val['nick']}','{$val['sort']}','cn','{$val['speaker_display']}');";
						break;
					case 'author':
						$sql.="insert into author(author_id,author_name,author_desc)";
						$sql.=" values('{$val['id']}','{$val['name']}','{$val['desc']}');";
						break;
					case 'group':
						$sql.="insert into usergroup(usergroup_id,usergroup_name)";
						$sql.=" values('{$val['id']}','{$val['name']}');";
						break;
					case 'mainpic':
						$preUrl=C("DOMAIN_NAME").__ROOT__.'/'."Public/Zip/".getLoginPid()."/";
						$sql.="insert into scrollpic(scrollpic_id,scrollpic_preUrl,scrollpic_endUrl,scrollpic_groupId,scrollpic_html,scrollpic_mainpic)";
						$sql.=" values('{$val['id']}','{$preUrl}','{$val['mainpic']}','{$val['groupId']}','{$val['html']}','null');";
						break;
					case 'information':
						if($val['url_type']==1)
							$val['url']=$val['url_editor'];
						else
							$val['url']=C('DOMAIN_NAME').__ROOT__.'/'.$val['url_upload'];
						$sql.="insert into res(res_id,res_title,res_desc,res_type,res_size,res_time,res_url,res_state)";
						$sql.=" values('{$val['id']}','{$val['title']}','{$val['desc']}','{$val['type']}','{$val['size']}','{$val['time']}','{$val['url']}',0);";
						break;
					case 'course':
						if($val['course_insetImage']!='')
							$val['course_insetImage']= C('DOMAIN_NAME').__ROOT__.'/'.$val['course_insetImage'];
						if($val['course_image']!='')
							$val['course_image']= C('DOMAIN_NAME').__ROOT__.'/'.$val['course_image'];
						if(date('Y-m-d',$val['course_startDate'])!=date('Y-m-d',$val['course_endDate']))
							$val['course_time'] = date('Y-m-d',$val['course_startDate']).' 一 '.date('m-d',$val['course_endDate']);
						else
							$val['course_time'] = date('Y-m-d',$val['course_startDate']);
						$agenda_id=M('course_agenda','','DB_MEETING')->where('course_id='.$val['course_id'])->select();
						$speaker_id=M('course_speaker','','DB_MEETING')->where('course_id='.$val['course_id'])->select();
						$res_id=M('course_res','','DB_MEETING')->where('course_id='.$val['course_id'])->select();

						$course_agenda='';
						foreach($agenda_id as $val_1){
							if($course_agenda==''){
								$course_agenda=$val_1['agenda_id'];
							}else{
								$course_agenda.='|'.$val_1['agenda_id'];
							}
						}
						$val['course_agenda']=$course_agenda;

						$course_res='';
						foreach($res_id as $val_2){
							if($course_res==''){
								$course_res=$val_2['res_id'];
							}else{
								$course_res.='|'.$val_2['res_id'];
							}
						}
						$val['course_res']=$course_res;

						$course_speaker='';
						foreach($speaker_id as $val_3){
							if($course_speaker==''){
								$course_speaker=$val_3['speaker_id'];
							}else{
								$course_speaker.='|'.$val_3['speaker_id'];
							}
						}
						$val['course_speaker']=$course_speaker;
						$sql.="insert into course(course_id,course_name,course_group,course_image,course_insetImage,course_startDate,course_endDate,course_agenda,course_speaker,course_res,course_time)";
						$sql.=" values('{$val['course_id']}','{$val['course_name']}','{$val['course_group']}','{$val['course_image']}','{$val['course_insetImage']}','{$val['course_startDate']}','{$val['course_endDate']}','{$val['course_agenda']}','{$val['course_speaker']}','{$val['course_res']}','{$val['course_time']}');";
						break;
				}
			}
		}
		return $sql;
	}


	//excel 导入
	public function excel_import(){

		if($_FILES['excel']['name'] == '') $this->error('没有文件');

		import('ORG.Net.UploadFile');
		$upload = new UploadFile();												//实例化上传类
		$upload->maxSize  = 1024*1024*2;     									//设置附件上传大小
		$upload->allowExts  = array('xls');   									//设置附件上传类型
		$upload->savePath =  'Public/phpExcel/';				//设置附件上传目录
		if(!$upload->upload()) {												//上传错误提示错误信息
			$this->error($upload->getErrorMsg());
		}else{																	//上传成功 获取上传文件信息
			$info =  $upload->getUploadFileInfo();
		};


		require_once 'Public/phpExcel/PHPExcel.php';
		require_once 'Public/phpExcel/PHPExcel/IOFactory.php';
		require_once 'Public/phpExcel/PHPExcel/Reader/Excel5.php';

		$inputFileName = $info[0]['savepath'].$info[0]['savename'];;

		$objReader = PHPExcel_IOFactory::createReader('Excel5');//use excel2007 for 2007 format
		$objPHPExcel = $objReader->load($inputFileName);
		$sheet = $objPHPExcel->getSheet(0);
		$highestRow = $sheet->getHighestRow(); // 取得总行数

		$sheetData = $objPHPExcel->getActiveSheet()->toArray(true,true,true,true);

		foreach($sheetData as $key=>$val){
			if($val['B']!='' || $val['B']=='密码' ){
				$data['audience_username'] 	    = $val['A']!=''?trim($val['A']):'';
				$data['audience_pwd'] 	    	= $val['B']!=''?trim($val['B']):'';
				$data['audience_name']  		= $val['C']!=''?trim($val['C']):'';
				$data['audience_tel']			= $val['D']!=''?trim($val['D']):'';
				$data['audience_email'] 		= $val['E']!=''?trim($val['E']):'';
				$data['audience_department'] 	= $val['F']!=''?trim($val['F']):'';
				$data['audience_position'] 	    = $val['G']!=''?trim($val['G']):'';
				$data['time_insert']			= time();
				$data['time_update']			= time();
				$data['time_delete']			= -1;
				$data['audience_state']			= 1;
				$dataArr[]=$data;
			}else{
				break;
			}
		}
		$i = 0;
		foreach($dataArr as $val){
			$re = M('audience_department','','DB_MEETING')->where('department_name="'.$val['audience_department'].'"')->getField('department_id');
			if(!empty($re)){
				$val['audience_department']=$re;
			}else{
				$data1['department_name'] = $val['audience_department'];
				$data1['time_insert'] = time();
				$data1['time_update'] = time();
				$data1['time_delete'] = -1;
				$val['audience_department']=M('audience_department','','DB_MEETING')->add($data1);
			}
			if( $rs = M('audience','','DB_MEETING')->add($val) )
			{
				D('Audience')->add_department_rds($rs,$val['audience_department']);
				$i++;
			}
		}
		$val = null ; unset($val);

		if((count($userNameError)+count($uidError))>0){
			$html='<table border="1" style="border-collapse:collapse;"><tr><td>编号</td><td>用户名</td><td>昵称</td><td>原因</td></tr>';
			if($userNameError != ''){
				$html.=$userNameError;
			}
			if($uidError != ''){
				$html.=$uidError;
			}
			$html.="</table>";
			file_put_contents('Public/phpExcel/log/log.php',$html);
		}
		echo "<a href='".__URL__."'>返回</a><br/>共{$highestRow}条数据,成功添加".$i."条,错误条数".($highestRow-$i).",log=> ".C('DOMAIN_NAME').__ROOT__."/Public/phpExcel/log/log.php";
	}

}	
?>
